package com.comboo.example.web.api;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * @author Sherman
 * created in 2018/12/19
 */
@JsonInclude
public class RequestPageWrapper<T> extends RequestWrapper<T> {

    @NotNull
    @Min(0)
    @JsonProperty
    private Integer pageNo;

    @NotNull
    @Min(0)
    @JsonProperty
    private Integer pageSize;

    /**
     * 排序类型，顺序跟排序字段一一对应
     */
    @JsonProperty
    private Sort.Direction[] directions;

    /**
     * 排序字段，顺序跟排序类型一一对应
     */
    @JsonProperty
    private String[] sortProperties;

    public Integer getPageNo() {
        return pageNo;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public Sort.Direction[] getDirections() {
        return directions;
    }

    public String[] getSortProperties() {
        return sortProperties;
    }

    @JsonIgnore
    public Sort getSort() {
        String[] properties = getSortProperties();
        if (properties != null && properties.length > 0) {
            Sort.Direction[] directions = getDirections();
            Sort.Order[] orders = new Sort.Order[properties.length];
            for (int i = 0; i < getSortProperties().length; i++) {
                if (directions == null || directions[i] == null) {
                    orders[i] = new Sort.Order(Sort.Direction.ASC, properties[i]);
                    continue;
                }
                orders[i] = new Sort.Order(directions[i], properties[i]);
            }
            return new Sort(orders);
        }
        return Sort.unsorted();
    }

    @JsonIgnore
    public Pageable getPageable() {
        if (getPageSize() == 0) {
            return PageRequest.of(getPageNo(), 20, getSort());
        }
        return PageRequest.of(getPageNo(), getPageSize(), getSort());
    }

}
